package model
{
	import flash.events.*;
	import flash.net.SharedObject;
	import flash.utils.*;
	
	import mx.controls.*;
	import mx.core.*;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.patterns.mediator.Mediator;
  	
	public class Square extends Mediator implements IMediator
	{
		private var so:SharedObject;
		private var piece:Piece;
		private var source:String;
		private var board:BoardMediator;
		
		private var xGrid:Number;
		private var yGrid:Number;
		private var occupied:Boolean;
		private var passable:Boolean = true;
		
		public function Square():void{
			so = SharedObject.getLocal('so');
			this.piece = so.data.empty;
			this.source = this.piece.getSource();
		}
		
		public function setBoard(board:BoardMediator, x:Number, y:Number):void{
			this.board = board;
			this.xGrid = x;
			this.yGrid = y;
		}
		
		public function addPiece(piece:Piece):void{
			this.piece = piece;
			this.source = this.piece.getSource();
			this.piece.setXY(this.xGrid, this.yGrid);
			this.occupied = true;
			so.data.temp = null;
		}
		
		public function removePiece():void{
			so.data.temp = this.piece;
			this.piece = so.data.empty;
			this.source = this.piece.getSource();
			this.occupied = false;
		}
		
		public function movePiece():void{
			var moveP:Piece = so.data.temp;
			
			if (moveP.move(this.xGrid, this.yGrid) && this.passable){
				addPiece(moveP);
			}
		}
		
		public function getPiece():Piece{
			return this.piece;
		}
		
		public function setPassable(p:Boolean):void{
			this.passable = p;
		}
		
		public function isPassable():Boolean{
			return this.passable;
		}
		
		public function setOccupied(o:Boolean):void{
			this.occupied = o;
		}
		
		public function isOccupied():Boolean{
			return this.occupied;
		}
		
		public function getSource():String{
			return this.source;
		}
		
		public function battle():void{
			var attacker:Piece = so.data.temp;
			var winner:Piece = attacker.attack(this.piece);
			
			if (winner != null){
				addPiece(winner);
			}
			else{
				addPiece(so.data.empty);
			}
		}
		
	}
}